package com.yjps.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yjps.common.message.Message;
import com.yjps.common.page.Pager;
import com.yjps.common.util.CommonUtil;
import com.yjps.common.util.ContantsUtil;
import com.yjps.system.model.*;
import com.yjps.system.service.CodeService;
import com.yjps.system.service.CodeTypeService;
import com.yjps.system.service.DemandService;
import com.yjps.system.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 需求控制类
 *     |--后台接口
 *           |--/system/demand/list  获取需求分页列表
 *           |--/system/demand/accept  受理需求请求
 *           |--/system/demand/getDemand  获得指定id的需求json对象
 *    |--前台接口
 *           |--/company/demand/edit.do  前台用户添加需求请求
 *           |--/company/demand/edit.do  用户请求需求编辑页面
 * Created by jessy on 2015/8/26.
 */
@Controller
public class DemandController {
    Logger log = LoggerFactory.getLogger(DemandController.class);
    @Autowired
    DemandService demandService;
    @Autowired
    UserService userService;
    @Autowired
    CodeTypeService codeTypeService;
    @Autowired
    CodeService codeService;

    /**
     * 获取分页需求列表
     * @param acceptResult 已受理/受理
     * @param model
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/system/demand/list",method = RequestMethod.GET)
    public String list(String acceptResult,Model model,HttpServletRequest request,HttpServletResponse response) throws Exception {
        Pager<Demand> pager = demandService.getDemandByPager(new Pager<Demand>(request, response),acceptResult);
        List<Demand> demands = pager.getList();
        CodeType codeType = codeTypeService.findCodeTypeByName(ContantsUtil.CODETYPE_HOUSE);
        System.out.println("codetype = " + codeType);
        Code code = null;
        if(demands != null && demands.size() > 0)
            for(Demand demand : demands){
                code = codeService.findCodeByKey(codeType.getId(),demand.getHouseType());
                if(code != null)
                    demand.setHouseTypeName(code.getCodeValue());
            }
        model.addAttribute(pager);
        return "system/demand/list";
    }

    /**
     * 用户请求需求编辑页面
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/company/demand/edit.do",method = RequestMethod.GET)
    public String edit(HttpServletResponse response){
        DemandCodeData codeData = new DemandCodeData();
        CodeType houseType = codeTypeService.findCodeTypeByName(ContantsUtil.CODETYPE_HOUSE);
        codeData.setHouse(codeService.getCodeByType(houseType.getId()));
        CodeType cityType = codeTypeService.findCodeTypeByName(ContantsUtil.CODETYPE_CITY);
        codeData.setCity(codeService.getCodeByType(cityType.getId()));
        CodeType countyType = codeTypeService.findCodeTypeByName(ContantsUtil.CODETYPE_COUNTY);
        codeData.setCounty(codeService.getCodeByType(countyType.getId()));
        CodeType townType = codeTypeService.findCodeTypeByName(ContantsUtil.CODETYPE_TOWN);
        codeData.setTown(codeService.getCodeByType(townType.getId()));
        CodeType areaType = codeTypeService.findCodeTypeByName(ContantsUtil.CODETYPE_AREA);
        codeData.setArea(codeService.getCodeByType(areaType.getId()));
        return new Message(true,"初始化需求页面",codeData).toJson();
    }

    /**
     * 添加需求
     * @param json
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/company/demand/edit.do",method = RequestMethod.POST)
    public String edit(@RequestParam(value = "json",required = true)String json,
                       @RequestParam(value = "id",required = true)String userId,HttpServletRequest request){
//        User user = (User) request.getSession().getAttribute("loginUser");
        System.out.println("json = " + json);
        JSONObject jsonObject = JSON.parseObject(json);
        String demandType = jsonObject.get("demandType").toString();
        String houseType = jsonObject.get("houseType").toString();
        String houseCity = jsonObject.get("houseCity").toString();
        String houseCounty = jsonObject.get("houseCounty").toString();
        String houseTown = jsonObject.get("houseTown").toString();
        String housePrice = jsonObject.get("housePrice").toString();
        String houseArea = jsonObject.get("houseArea").toString();
        Demand demand = new Demand();
        demand.setDemandType(Integer.parseInt(demandType));
        demand.setHouseArea(houseArea);
        demand.setHousePrice(BigDecimal.valueOf(Long.parseLong(housePrice)));
        demand.setHouseCity(houseCity);
        demand.setHouseCounty(houseCounty);
        demand.setHouseTown(houseTown);
        demand.setHouseType(houseType);
        demand.setUserId(Integer.parseInt(userId));/**/
        demand.setDemandTime(CommonUtil.dataToString(new Date()));
        demand.setDemandState(1);
        demand.setAcceptResult(0);
        demand.setAcceptTime("");
        demand.setIsValid(1);
        int id = demandService.save(demand);
        /*model.addAttribute("demand",demand);*/
        Message message = null;
        if(id>0) {
            message = new Message(true, "需求编辑成功！", demand);
        }else{
            message = new Message(false, "需求编辑失败！");

        }
        return message.toJson();
    }

    /**
     * 受理需求
     * @param id
     * @return
     */
    @RequestMapping(value = "/system/demand/accept",method =RequestMethod.GET)
    public String accept(@RequestParam(value = "id",required = true)String id){
        Demand demand = demandService.getDemand(Integer.parseInt(id));
        demand.setAcceptResult(1);
        demand.setAcceptTime(CommonUtil.dataToString(new Date()));
        demandService.updateDemand(demand);
        return "redirect:/system/demand/list";
    }

    /**
     * 获得需求json
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/system/demand/getDemand",method = RequestMethod.GET)
    public String getDemand(@RequestParam(value = "id",required = true)String id){
        Demand demand = demandService.getDemand(Integer.parseInt(id));
        User u = userService.findUser(demand.getUserId());
        demand.setUsername(u.getUsername());
        String jsonStr = JSON.toJSONString(demand);
        return jsonStr;
    }

    @RequestMapping(value = "/system/demand/delete",method = RequestMethod.GET)
    public String delete(@RequestParam(value = "id",required = true)String id){
        log.debug("delete user id " + id);
        demandService.delete(Integer.parseInt(id));
        return "redirect:/system/demand/list";
    }
}
